<?php
/**
 * Created by PhpStorm.
 * User: TianFeng
 * Date: 2017/12/27
 * Time: 16:27
 */
namespace app\merchant\controller;

use app\common\lib\Encryption;
use app\common\lib\MyController;
use app\common\lib\Page;
use app\common\upyun\Config;
use app\merchant\model\BorrowRequest;
use app\merchant\model\BorrowRequestDetail;
use app\merchant\model\TpBorrower;
use app\merchant\model\User;
use app\common\lib\Excel2Array;
use app\merchant\model\UserCompany;
use app\merchant\service\UserService;
use think\Db;
use think\Exception;
use think\Request;
use app\common\lib\Constant;

class  Borrower extends MyController {
    //个人借款人 消费贷列表
    public function jiemitest(){
        header("Content-type: text/html; charset=utf-8");
        $int_page = Request::instance()->get('str');
        $str = Encryption::tiriDecode($int_page);
        echo $str;exit;
    }

    //添加多个借款人模板 excle
    public function multipleAdd(){
        return view('Borrower/multipleAdd');
    }

    //保存 批量添加
    public function doAdd(Request $request){
        header("Content-type: text/html; charset=utf-8");
        try {
            $file_company = $request->file('company_borrower');
            if ($file_company==null){
                throw new Exception(json_encode(['请选择上传的文件！']));
            }
            $arr_result = $this->_validateExcelFile($file_company);
            $int_bachNum = BorrowRequest::generateBatchNum($this->_Uid); //批次号
            $excle_key_map = array_merge($arr_result['excel_key_map']['sql_map'],$arr_result['excel_key_map']['json_map']);
            switch ($arr_result['excel_type'] ){
                case BorrowRequest::TYPE_PERSON_SHOPPING:
                    $submit_url = url('borrower/insertPersonShopping');break;
                //    '/merchant/borrower/insertPersonShopping';
                case BorrowRequest::TYPE_PERSON_CAR:
                    $submit_url = '/merchant/borrower/insertPersonCar';break;
                case BorrowRequest::TYPE_COMPANY:
                    $submit_url = '/merchant/borrower/insertCompanyBorrow';break;
            }
            $this->assign('excle_key_map',$excle_key_map);
            $this->assign('excle_type',$arr_result['excel_type']);
            $this->assign('submit_url',$submit_url);
            $this->assign('bach_num', $int_bachNum);
            $this->assign('result_date', $arr_result['data']);
            $this->assign('count', count($arr_result['data']));
            $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
            $this->assign('bank_code_list', Config('bank_list'));
            return view('Borrower/borrowRequestInsert');
        }catch (\Exception $exception){
            return view('Borrower/multipleAdd',[
                'has_error'=>1,
                'message'=> $exception->getMessage()
            ]);
        }
    }

    //单条插入借款人 消费贷 车贷 ajax
    public function insertPersonShopping(){
        try{
            if (! $this->checkInsertAccess(BorrowRequest::TYPE_PERSON_SHOPPING)){
                throw new \Exception('无此权限');
            }
            $data = Request::instance()->post('info/a');
            //$data = json_decode($data, true);
            $data = reset($data);

            if (!$data){
                throw new \Exception('获取页面值错误！');
            }

            $validate_result = BorrowRequest::validateExcelData(BorrowRequest::TYPE_PERSON_SHOPPING,$data);
            if ($validate_result) {
                return $this->returnData(1, implode(';<br>',$validate_result),  [
                    'arr_errorMsg'=>$validate_result,
                ]);
            }

            $data['money'] = floor($data['money']/100)*100;
            $user = User::get(['user_phone' => $data['mobile']]);

            if (!$user){ //没有注册 调用注册接口
                $obj_regResult = UserService::borrowUserReg($data['mobile'], $this->_Uid);
                if ($obj_regResult['code'] !=0){
                    throw new \Exception($obj_regResult['msg']);
                }
                //调用实名认证接口
                $obj_relname = UserService::userRealeNameObj($obj_regResult['data']['user_id'], $data['name'],$data['idcard']);

                if ($obj_relname['code'] != 0){
                    throw new \Exception($obj_relname['msg']);
                }
                $user = User::get(['user_phone' => $data['mobile']]);
            }else{
                if (!$user->real_name){ //未实名 调用实名
                    //调用实名认证接口
                    $obj_relname = UserService::userRealeNameObj($user->uid, $data['name'],$data['idcard']);
                    if ($obj_relname['code'] != 0){
                        throw new \Exception($obj_relname['msg']);
                    }
                }else{
                    if ($user->idcard!= $data['idcard']){
                        throw new \Exception("身份证与原实名信息不符合！请核对手机号或身份信息！");
                    }
                }
            }

            $map_excelSqlKey = BorrowRequest::getExcelFiledMap($data['excle_type']);
            $json_date = [];
            foreach ($data as $key => $val) {
                if (array_key_exists($key, $map_excelSqlKey['sql_map'])) {
                    $sql_field = $map_excelSqlKey['sql_map'][$key]['field'];
                    $sql_date[$sql_field] = $val;
                }
                if (array_key_exists($key, $map_excelSqlKey['json_map'])) {
                    $this->_formatJsonFieldGroup($json_date, $key, $val, $map_excelSqlKey);
                }
            }
            $sql_date['batch_number'] = $data['batch_number'];
            $sql_date['borrow_uid'] =$user->uid;
            $sql_date['type'] =BorrowRequest::TYPE_PERSON_SHOPPING;
            $sql_date['merchant'] =$this->_Uid;
            $sql_date['create_time'] =time();

            Db::startTrans();
            try{
                $model_BorrowRequest = new BorrowRequest();
                $res_id = $model_BorrowRequest->insertGetId($sql_date);

                $model_BorrowRequestDetail = new BorrowRequestDetail();
                $arr_BorrowRequestDetail['borrow_request_id'] = $res_id;
                $arr_BorrowRequestDetail['extra_filed'] = json_encode($json_date);
                $model_BorrowRequestDetail->insertGetId($arr_BorrowRequestDetail);
                Db::commit();
                if (!$res_id){
                    return $this->returnData(1, '保存失败 稍后重试');
                }
                return $this->returnData(0, '保存成功');
            }catch(\Exception $exception){
                Db::rollback();
                return $this->returnData(1, '保存失败 稍后重试');
            }
        }catch (\Exception $exception){
            return $this->returnData(1, $exception->getMessage());
        }
    }

    //单条插入借款人 消费贷 车贷 ajax
    public function insertPersonCar(){
        try{
            if (!$this->checkInsertAccess(BorrowRequest::TYPE_PERSON_CAR)){
                throw new \Exception('无此权限');
            }
            $data = Request::instance()->post('info/a');
            //$data = json_decode($data, true);
            $data = reset($data);
            $msg = '';
            if (!$data){
                throw new \Exception('获取页面值错误！');
            }
            $validate_result = BorrowRequest::validateExcelData(BorrowRequest::TYPE_PERSON_CAR,$data);
            if ($validate_result) {
                return $this->returnData(1, implode(';<br>',$validate_result),  [
                    'arr_errorMsg'=>$validate_result,
                ]);
            }
            $data['money'] = floor($data['money']/100)*100;
            $user = User::get(['user_phone' => $data['mobile']]);
            if (!$user){ //没有注册 调用注册接口
                $obj_regResult = UserService::borrowUserReg($data['mobile'], $this->_Uid);
                if ($obj_regResult['code'] !=0){
                    throw new \Exception($obj_regResult->msg);
                }
                //调用实名认证接口
                $obj_relname = UserService::userRealeNameObj($obj_regResult['data']['user_id'], $data['name'],$data['idcard']);

                if ($obj_relname['code'] != 0){
                    throw new \Exception($obj_relname['msg']);
                }
                $user = User::get(['user_phone' => $data['mobile']]);
            }else{
                if (!$user->idcard){ //未实名 调用实名
                    $obj_service = new UserService();
                    //调用实名认证接口
                    $obj_relname = UserService::userRealeNameObj($user->uid, $data['name'],$data['idcard']);
                    if ($obj_relname['code'] != 0){
                        throw new \Exception($obj_relname['msg']);
                    }
                }
                else{
                    if ($user->idcard!=$data['idcard']){
                        throw new \Exception("身份证与原实名信息不符合！请核对手机号或身份信息！");
                    }
                }
            }

            $map_excelSqlKey = BorrowRequest::getExcelFiledMap($data['excle_type']);
            $json_date = [];
            foreach ($data as $key => $val) {
                if (array_key_exists($key, $map_excelSqlKey['sql_map'])) {
                    $sql_field = $map_excelSqlKey['sql_map'][$key]['field'];
                    $sql_date[$sql_field] = $val;
                }
                if (array_key_exists($key, $map_excelSqlKey['json_map'])) {
                    $this->_formatJsonFieldGroup($json_date, $key, $val, $map_excelSqlKey);
                }
            }
            $sql_date['batch_number'] = $data['batch_number'];
            $sql_date['borrow_uid'] =$user->uid;
            $sql_date['type'] =BorrowRequest::TYPE_PERSON_CAR;
            $sql_date['merchant'] =$this->_Uid;
            $sql_date['create_time'] =time();

            Db::startTrans();
            try{
                $model_BorrowRequest = new BorrowRequest();
                $res_id = $model_BorrowRequest->insertGetId($sql_date);

                $model_BorrowRequestDetail = new BorrowRequestDetail();
                $arr_BorrowRequestDetail['borrow_request_id'] = $res_id;
                $arr_BorrowRequestDetail['extra_filed'] = json_encode($json_date);
                $model_BorrowRequestDetail->insertGetId($arr_BorrowRequestDetail);
                Db::commit();
                if (!$res_id){
                    return $this->returnData(1, '保存失败 稍后重试');
                }
                return $this->returnData(0, '保存成功');
            }catch(\Exception $exception){
                Db::rollback();
                return $this->returnData(1, '保存失败 稍后重试');
            }
        }catch (\Exception $exception){
            return $this->returnData(1, $exception->getMessage());
        }
    }

    //单条添加 企业贷信息 ajax
    public function insertCompanyBorrow(){
        try{
            if (!$this->checkInsertAccess(BorrowRequest::TYPE_COMPANY)){
                throw new \Exception('无此权限');
            }
            $data = Request::instance()->post('info/a');
            $data = reset($data);
            $msg = '';
            if (!$data){
                throw new \Exception('获取页面值错误！');
            }
            $validate_result = BorrowRequest::validateExcelData(BorrowRequest::TYPE_COMPANY,$data);
            if ($validate_result) {
                return $this->returnData(1, implode(';<br>',$validate_result), [
                        'arr_errorMsg'=>$validate_result,
                    ]);
            }

            $data['money'] = floor($data['money']/100)*100;
            //企业借款人开户
            $arr_companyInfo = [
                'company_name'=>$data['company_name'], //企业名称
                'license_no'=>$data['license_no'], //营业执照号
                'license_address'=>$data['license_address'],//营业执照所在地
                'address'=>$data['address'], //企业地址
                'bank_account_no'=>$data['bank_account_no'],//开户行卡号
                'bank_branch' => $data['bank_branch'], //开户支行名称
                'license_expire_date'=>$data['license_expire_date'],//营业执照有效期
                'business_scope'=>$data['business_scope'], //营业范围
                'telephone'=>$data['telephone'],//联系电话
                'organization_no'=>$data['organization_no'],//组织机构代码
                'summary'=>$data['company_synopsis'], //企业简介
                'website'=>$data['website'],//网站网址
                'legal_person'=>$data['legal_person'], //企业法人
                'legal_person_phone'=>$data['mobile'],//法人手机号码
                'cert_no'=>$data['idcard'],//法人证件号码
                'bank_code'=>$data['bank_code'], //银行编号
                'province'=>$data['bank_location'], //开户行省份
                'city'=>$data['bank_city'],//bank_city
                'email'=>$data['email'],//联系邮箱
            ];
            $user = User::get(['user_phone' => $data['mobile']]);

            if (!$user){ //没有注册 调用注册接口$int_phone,$str_email,$int_userType, $int_role
                $obj_regResult = UserService::borrowUserReg($data['mobile'],$this->_Uid, '123456',User::USER_TYPE_COMPANY);
                $user = User::get(['user_phone' => $data['mobile']]);
                if ($obj_regResult['code'] !=0 ){
                    throw new \Exception($obj_regResult['msg']);
                }
                $user = User::get(['user_phone' => $data['mobile']]);
            }
            if ($user->user_type != User::USER_TYPE_COMPANY || $user->role != User::ROLE_BORROWER){
                throw new \Exception('该手机号已经被其他类型用户注册，不能注册为企业借款人！');
            }
            $user_company = UserCompany::get(['user_id' => $user->uid ]);
            if(!$user_company){
                $image = UserCompany::getImage($data['license_file_src'], $data['org_no_src'],$data['tax_no_src'],
                    $data['front_card_src'],$data['back_card_src'],$data['open_account_no_src']);
                $res = UserService::setCompanyInfo($arr_companyInfo, $user->uid,$data['email'],$image);
            }else{
                if ($user_company->cert_no != $data['idcard']){
                    throw new \Exception("法人证件号与原实名信息不符合！请核对手机号或身份信息！");
                }
            }
            $map_excelSqlKey = BorrowRequest::getExcelFiledMap($data['excle_type']);
            $json_date = [];
            foreach ($data as $key => $val){
                if (array_key_exists($key, $map_excelSqlKey['sql_map'])){
                    $sql_field = $map_excelSqlKey['sql_map'][$key]['field'];
                    $sql_date[$sql_field] = $val;
                }
                if (array_key_exists($key, $map_excelSqlKey['json_map'])){
                    $this->_formatJsonFieldGroup($json_date, $key, $val, $map_excelSqlKey);
                }
            }
            $sql_date['borrow_uid'] = $user->uid;
            $sql_date['batch_number'] = $data['batch_number'];
            $sql_date['type'] =BorrowRequest::TYPE_COMPANY;
            $sql_date['merchant'] =$this->_Uid;
            $sql_date['create_time'] =time();

            Db::startTrans();
            try{
                $model_BorrowRequest = new BorrowRequest($sql_date);
                $model_BorrowRequest->save();
                $arr_BorrowRequestDetail['borrow_request_id'] = $model_BorrowRequest->id;
                $arr_BorrowRequestDetail['extra_filed'] = json_encode($json_date);
                $model_BorrowRequestDetail = new BorrowRequestDetail($arr_BorrowRequestDetail);
                $model_BorrowRequestDetail->save();
                Db::commit();
            }catch(\Exception $exception){
                Db::rollback();
                return $this->returnData(1, '保存失败 稍后重试');
            }
            return $this->returnData(0, '保存成功');
        }catch (\Exception $exception){
            return $this->returnData(1, $exception->getMessage());
        }
    }

    //个人借款人车贷插入页面
    public function personCarDoAdd(){
        return view('Borrower/borrowRequestInsert');
    }

    private function _validateExcelFile($file_info){
        $info = $file_info->validate(['size'=>15678,'ext'=>'xlsx']);
   /*     $str_path = APP_ROOT.'\tmp\excel';
        $info = $file_info->validate(['size'=>15678,'ext'=>'xlsx'])
            ->move($str_path);*/
        if ($info==false){
            throw new \Exception(json_encode([$file_info->getError()]));
        }
        $str_filePath = $file_info->getPathname();
        $obj_excel = new Excel2Array();
        $arr_result= $obj_excel->read($str_filePath);
        $int_i = 0;
        if (count($arr_result)<2){
            throw new \Exception(json_encode(['文件没有数据！']));
        }
        $result = [];
        $data = [];
        foreach ($arr_result as $key=>$val){
            if ($int_i == 0){
                //preg_match_all ("/<(.*)>/U", (string)$val[0], $pat_array);
                preg_match("/<(.*)>/U", (string)$val[0], $pat_array);
                $str_type = end($pat_array);
                $arr_keyMap = BorrowRequest::getExcelFiledMap($str_type);
                $arr_keys=[];
                foreach ($val as $kk=>$vv){
                    preg_match("/#(.*)#/U", $vv, $pat_array);
                    $str_temp = end($pat_array);
                    if (!$str_temp){
                        throw new \Exception(json_encode(['<模板格式错误 请下载标准模板>']));
                    }
                    if (array_key_exists($str_temp, $arr_keyMap['sql_map']) ||
                        array_key_exists($str_temp, $arr_keyMap['json_map']) ){
                        $arr_keys[$kk]= $str_temp;
                    }else{
                        throw new \Exception(json_encode([$str_temp.'#模板格式错误 请下载标准模板#']));
                    }
                }
                $int_i++;
            }
            else{
                $excle_key_map = array_merge($arr_keyMap['sql_map'],$arr_keyMap['json_map']);
                $bool_rowIsAllEmpry = true;
                foreach ($val as $kk=>$vv){
                    $str_key = $arr_keys[$kk];
                    $arr_tempdata[$str_key]=trim($vv);
                    if($arr_tempdata[$str_key]){
                        $bool_rowIsAllEmpry = false;
                    }
                }
                if (!$bool_rowIsAllEmpry){ // 如果该行都是空行 则不读取该行
                    foreach ($arr_tempdata as $kk =>$vv){
                        if (!$arr_tempdata[$kk]){//没有赋值给默认值
                            if (isset($excle_key_map[$kk]['default'])){
                                $arr_tempdata[$kk]=$excle_key_map[$kk]['default'];
                            }
                        }
                    }
                    $data[$key] = $arr_tempdata;
                }

            }
        }
        chmod($str_filePath,777);
        @unlink($str_filePath);
        $result['data'] = $data;
        $result['excel_type'] = $str_type;
        $result['excel_key_map'] = $arr_keyMap;
        return $result;
    }

    //个人借款人 消费贷列表
    public function getPersonBorrowList(){
        $int_page = Request::instance()->get('page', 1);
        $int_num = Request::instance()->get('num'); //批次号
        $user_name = Request::instance()->get('user_name'); //姓名
        $idcard = Request::instance()->get('idcard'); //证件号
        $mobile = Request::instance()->get('mobile'); //手机号
        $int_status = Request::instance()->get('status'); //状态
        $str_startTime = Request::instance()->get('start_time');//开始时间
        $str_endTime = Request::instance()->get('end_time');//结束时间

        $where['bq.merchant'] = ['=', $this->_Uid];
        $where['bq.type'] = ['=', BorrowRequest::TYPE_PERSON_SHOPPING];
        if ($int_num){
            $where['bq.batch_number'] = ['=', $int_num];
            $this->assign('num', $int_num);
        }
        if ($user_name){
            $where['user.real_name'] = ['=', $user_name];
            $this->assign('user_name', $user_name);
        }
        if ($idcard){
            $where['user.idcard'] = ['=', $idcard];
            $this->assign('idcard', $idcard);
        }
        if ($mobile){
            $where['user.user_phone'] = ['=', $mobile];
            $this->assign('mobile', $mobile);
        }
        if ($str_startTime){
            $where['bq.create_time'] = ['>=', strtotime($str_startTime)];
            $this->assign('start_time', $str_startTime);
        }
        $where2=[];
        if ($str_endTime){
            $where2['bq.create_time'] = ['<=', strtotime($str_endTime)];
            $this->assign('end_time', $str_endTime);
        }

        $arr_statusConfig = [
            0 => '全部',
            1 => '待审核',
            2 => '审核通过',
            3 => '审核不通过',
            4 => '未实名未设置支付密码',
            5 => '未实名',
        ];
        if ($int_status){
            switch ($int_status){
                case 1:  $where['bq.status'] = ['=', BorrowRequest::STATUS_DEFAULT];break;
                case 2:  $where['bq.status'] = ['=', BorrowRequest::STATUS_YES];break;
                case 3:  $where['bq.status'] = ['=', BorrowRequest::STATUS_NO];break;
                case 4:  $where['user.third_uid'] = ['=', ''];break;
                case 5:  $where['user.idcard'] = ['=', ''];break;
            }
            $this->assign('status', $int_status);
        }

        $list = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid' )
            ->page($int_page, Constant::PAGE_SIZE_MID)
            ->field([
                'user.uid as uid',
                'user.real_name as real_name',
                'user.idcard as idcard',
                'user.third_uid as third_uid',
                'user.user_phone as user_phone',
                'user.is_set_pay_password as is_set_pay_password',
                'bq.id as bq_id',
                'bq.batch_number as batch_number',
                'bq.money as money',
                'bq.duration as duration',
                'bq.repayment_type as repayment_type',
                'bq.status as status',
                'bq.create_time as create_time',
                'bq.update_time as update_time',
            ])
            ->order('bq_id','DESC')
            ->select();

        $count = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid' )
            ->count();
        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $int_page);

        $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
        $this->assign('status_map', BorrowRequest::statusMap());
        $this->assign('map_status', $arr_statusConfig);
        $this->assign('list', $list);
        $this->assign('pageElem', $paginator);
        return view('Borrower/personBorrowList');
    }

    //原始借款需求详情
    public function getPersonBorrowDetail(){
        try{
            $int_id = Request::instance()->get('id' );
            $res_bq = BorrowRequest::get(['id'=>$int_id,'merchant'=>$this->_Uid]);
            if (!$int_id || !$res_bq){
                throw new \Exception('不存在该详情');
            }
            $model_bq = new BorrowRequest();
            if( $res_bq->type == BorrowRequest::TYPE_COMPANY){
                $info =$model_bq->getCompanyBorrowRequestDetail($int_id);
            }else{
                $info =$model_bq->getBorrowRequestDetail($int_id);
            }

            if ($info->extra_filed){
                $extra_filed = json_decode($info->extra_filed, true);
                //数据结构修改了，做法也得修改 2018-05-10
                $items = [];
                foreach ($extra_filed as $val) {
                    foreach ($val['items'] as $value) {
                        $items[$value['field']] = $value['value'];
                    }
                }
                $arr_extrafiled = $items;
            }else{
                $arr_extrafiled = [];
            }
            $arr_excleKeyMap = BorrowRequest::getExcelFiledMap($info->bq_type);
            $this->assign('info', $info);
            $this->assign('excleMap', $arr_excleKeyMap);
            $this->assign('extra_filed', $arr_extrafiled );
            $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
            $this->assign('status_map', BorrowRequest::statusMap());
            $this->assign('upyun_prefix', Config('upyun_config.upaiyun'));
            return view('Borrower/borrowDetail');
            //return view('Borrower/personBorrowDetail');
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    //编辑原始借款信息editPersonShoppingBorrow
    public function editBorrowDetail(){
        try{
            $int_id = Request::instance()->get('id' );
            $res_bq = BorrowRequest::get(['id'=>$int_id,'merchant'=>$this->_Uid]);
            if (!$int_id || !$res_bq){
                throw new \Exception('不存在该详情');
            }

            if ($res_bq->status == BorrowRequest::STATUS_YES){
                throw new \Exception('审核通过无法修改');
            }
            $model_bq = new BorrowRequest();
            if( $res_bq->type == BorrowRequest::TYPE_COMPANY){
                $info = $model_bq->getCompanyBorrowRequestDetail($int_id);
            }else{
                $info = $model_bq->getBorrowRequestDetail($int_id);
            }

            if ($info->extra_filed){
                $extra_filed = json_decode($info->extra_filed, true);
                //数据结构修改了，做法也得修改 2018-05-10
                $items = [];
                foreach ($extra_filed as $val) {
                    foreach ($val['items'] as $value) {
                        $items[$value['field']] = $value['value'];
                    }
                }
                $arr_extrafiled = $items;
            }else{
                $arr_extrafiled = [];
            }
            $arr_excleKeyMap = BorrowRequest::getExcelFiledMap($info->bq_type);
            $this->assign('info', $info);
            $this->assign('upyun_prefix', Config('upyun_config.upaiyun'));
            $this->assign('extra_filed', $arr_extrafiled);
            $this->assign('excleMap', $arr_excleKeyMap);
            $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
            $this->assign('status_map', BorrowRequest::statusMap());
            $this->assign('type_personshop', BorrowRequest::TYPE_PERSON_SHOPPING);
            $this->assign('type_personcar', BorrowRequest::TYPE_PERSON_CAR);
            $this->assign('type_company', BorrowRequest::TYPE_COMPANY);
            return view('Borrower/editBorrowDetail');
        }
        catch (\Exception $exception){
            echo $exception->getMessage();exit;
            //$this->error($exception->getMessage());
        }
    }

    /**
     * 保存编辑 原始借款请求 update by abao on 2018-05-21
     * @return type
     * @throws \Exception
     */
    public function doEditBorrowDetail()
    {
        // 启动事务（更新了好几个数据表）
        Db::startTrans();
        try{
            //post数据（图片除外）
            $data = Request::instance()->post('info/a');
            //身份证图片
            $str_idcardFround = Request::instance()->post('idcard_fornt_src');
            $str_idcardBackend = Request::instance()->post('idcard_backend_src');
            $int_type = $data['bq_type'];

            $res_bq = BorrowRequest::get(['id'=>$data['bq_id'],'merchant'=>$this->_Uid]);
            if (!$res_bq){
                throw new \Exception('不存在该借款信息');
            }

            if ($res_bq->status == BorrowRequest::STATUS_YES){
                throw new \Exception('审核通过无法修改');
            }
            
            //因为要重新生成，数据库原先保存的也没必要取出来了
            /*
            $obj_bqDetail = $model_bqDetail->where(['borrow_request_id'=>$data['bq_id']])->find();
            if ($obj_bqDetail){
                $arr_extraFiled = json_decode($obj_bqDetail->extra_filed,true);
                if (!$arr_extraFiled){
                    $arr_extraFiled = [];
                }
            }
            */
            $map_keys = BorrowRequest::getExcelFiledMap($int_type);
            $arr_sqlFields = array_column($map_keys['sql_map'],'field');
            $arr_jsonFields = array_column($map_keys['json_map'],'field');
            //其它图片信息
            foreach ($arr_jsonFields as $key=>$val){
                $file_src = Request::instance()->post($val.'_src');
                if ($file_src){
                    //$arr_extraFiled[$val] = $file_src;
                    $data[$val] = $file_src; //本意是要放入请求参数里面吧
                }
            }
            $map_field = array_combine($arr_jsonFields, $map_keys['json_map']);//生成新的数组，以field为键，json_map为值
            
            $arr_updateSqlFiled = [];//更新sql_map
            $arr_updateSqlFiled['update_time'] = time();
            $arr_extraFiled = [];//更新json_map
            $map_jsonFieldsGroup = $map_keys['json_filed_group_map'];
            foreach ($data as $key=>$value){
                if (in_array($key, $arr_sqlFields)){
                    $arr_updateSqlFiled[$key] =  $value;
                }
                //格式化扩展字段 json格式
                if (in_array($key, $arr_jsonFields)){
                    $int_groupid = $map_field[$key]['group_id'];
                    if(!array_key_exists($int_groupid, $arr_extraFiled)){ //如果没有这个组，则新加这个组
                        $arr_extraFiled[$int_groupid] = $map_jsonFieldsGroup[$int_groupid];
                        $arr_extraFiled[$int_groupid]['items'] = [];
                    }
                    //重新生成items
                    $temp = [
                        'title' => $map_field[$key]['title'],
                        'field' => $map_field[$key]['field'],
                        'value' => $value
                    ];
                    array_push($arr_extraFiled[$int_groupid]['items'],$temp );
                }
            }
            
            //更新tp_borrow_request
            $model_bq = new BorrowRequest();
            $model_bq->update($arr_updateSqlFiled,['id'=>$data['bq_id']]);
            //更新tp_borrow_request_detail
            $model_bqDetail = new BorrowRequestDetail();
            $model_bqDetail->update(['extra_filed'=>json_encode($arr_extraFiled)], ['borrow_request_id'=>$data['bq_id'] ]);
            //更新tp_borrower
            $res = BorrowRequest::where('id', $data['bq_id'])->find();;
            $arr_borrower =[];
            $arr_update['uid'] = $res->borrow_uid;
            if ($str_idcardFround){
                $arr_borrower = ['uid'=>$res->borrow_uid];
                $arr_update['fornt_card'] = $str_idcardFround;
            }
            if ($str_idcardBackend){
                $arr_borrower = ['uid'=>$res->borrow_uid];
                $arr_update['back_card'] = $str_idcardBackend;
            }
            if ($arr_borrower){
                $res = TpBorrower::updateInsert($arr_borrower,$arr_update);
            }
            // 提交事务
            Db::commit(); 
            return view('Widgets/success');
        }catch (\Exception $exception){
            // 回滚事务
            Db::rollback();
            return $this->error($exception->getMessage());
        }

    }

    //个人借款人 车贷列表
    public function getPersonCarBorrowList(){
        $int_page = Request::instance()->get('page', 1);
        $int_num = Request::instance()->get('num'); //批次号
        $user_name = Request::instance()->get('user_name'); //姓名
        $idcard = Request::instance()->get('idcard'); //证件号
        $mobile = Request::instance()->get('mobile'); //手机号
        $int_status = Request::instance()->get('status'); //状态
        $str_startTime = Request::instance()->get('start_time');//开始时间
        $str_endTime = Request::instance()->get('end_time');//结束时间

        $where['bq.merchant'] = ['=', $this->_Uid];
        $where['bq.type'] = ['=', BorrowRequest::TYPE_PERSON_CAR];
        if ($int_num){
            $where['bq.batch_number'] = ['=', $int_num];
            $this->assign('num', $int_num);
        }
        if ($user_name){
            $where['user.real_name'] = ['=', $user_name];
            $this->assign('user_name', $user_name);
        }
        if ($idcard){
            $where['user.idcard'] = ['=', $idcard];
            $this->assign('idcard', $idcard);
        }
        if ($mobile){
            $where['user.user_phone'] = ['=', $mobile];
            $this->assign('mobile', $mobile);
        }

        if ($str_startTime){
            $where['bq.create_time'] = ['>=', strtotime($str_startTime)];
            $this->assign('start_time', $str_startTime);
        }
        $where2=[];
        if ($str_endTime){
            $where2['bq.create_time'] = ['<=', strtotime($str_endTime)];
            $this->assign('end_time', $str_endTime);
        }

        $arr_statusConfig = [
            0 => '全部',
            1 => '待审核',
            2 => '审核通过',
            3 => '审核不通过',
            4 => '未实名未设置支付密码',
            5 => '未实名',
        ];
        if ($int_status){
            switch ($int_status){
                case 1:  $where['bq.status'] = ['=', BorrowRequest::STATUS_DEFAULT];break;
                case 2:  $where['bq.status'] = ['=', BorrowRequest::STATUS_YES];break;
                case 3:  $where['bq.status'] = ['=', BorrowRequest::STATUS_NO];break;
                case 4:  $where['user.third_uid'] = ['=', ''];break;
                case 5:  $where['user.idcard'] = ['=', ''];break;
            }
            $this->assign('status', $int_status);
        }

        $list = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid' )
            ->page($int_page, Constant::PAGE_SIZE_MID)
            ->field([
                'user.uid as uid',
                'user.real_name as real_name',
                'user.idcard as idcard',
                'user.third_uid as third_uid',
                'user.user_phone as user_phone',
                'user.is_set_pay_password as is_set_pay_password',
                'bq.id as bq_id',
                'bq.batch_number as batch_number',
                'bq.money as money',
                'bq.duration as duration',
                'bq.repayment_type as repayment_type',
                'bq.status as status',
                'bq.create_time as create_time',
                'bq.update_time as update_time',
            ])
            ->order('bq_id','DESC')
            ->select();

        $count = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid' )
            ->count();
        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $int_page);

        $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
        $this->assign('status_map', BorrowRequest::statusMap());
        $this->assign('map_status', $arr_statusConfig);
        $this->assign('list', $list);
        $this->assign('pageElem', $paginator);
        return view('Borrower/personCarBorrowList');
    }

    //企业贷列表
    public function getCompanyBorrowList(){
        $int_page = Request::instance()->get('page', 1);
        $int_num = Request::instance()->get('num'); //批次号
        $company_name = Request::instance()->get('company_name'); //企业名称
        $int_status = Request::instance()->get('status'); //状态
        $str_startTime = Request::instance()->get('start_time');//开始时间
        $str_endTime = Request::instance()->get('end_time');//结束时间

        $where['bq.merchant'] = ['=', $this->_Uid];
        $where['bq.type'] = ['=', BorrowRequest::TYPE_COMPANY];
        if ($int_num){
            $where['bq.batch_number'] = ['=', $int_num];
            $this->assign('num', $int_num);
        }
        if ($company_name){
            $where['company.company_name'] = ['like', '%'.$company_name.'%'];
            $this->assign('company_name', $company_name);
        }
        if ($str_startTime){
            $where['bq.create_time'] = ['>=', strtotime($str_startTime)];
            $this->assign('start_time', $str_startTime);
        }
        $where2=[];
        if ($str_endTime){
            $where2['bq.create_time'] = ['<=', strtotime($str_endTime)];
            $this->assign('end_time', $str_endTime);
        }

        $arr_statusConfig = [
            0 => '全部',
            1 => '待审核',
            2 => '审核通过',
            3 => '审核不通过',
            4 => '未实名未设置支付密码',
            5 => '未实名',
        ];
        if ($int_status){
            switch ($int_status){
                case 1:  $where['bq.status'] = ['=', BorrowRequest::STATUS_DEFAULT];break;
                case 2:  $where['bq.status'] = ['=', BorrowRequest::STATUS_YES];break;
                case 3:  $where['bq.status'] = ['=', BorrowRequest::STATUS_NO];break;
                case 4:  $where['user.third_uid'] = ['=', ''];break;
                case 5:  $where['user.idcard'] = ['=', ''];break;
            }
            $this->assign('status', $int_status);
        }

        $list = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid','left' )
            ->join('tp_user_company company', 'bq.borrow_uid = company.user_id','left' )
            ->page($int_page, Constant::PAGE_SIZE_MID)
            ->field([
                'user.uid as uid',
                'user.real_name as real_name',
                'user.idcard as idcard',
                'user.third_uid as third_uid',
                'user.user_phone as user_phone',
                'user.is_set_pay_password as is_set_pay_password',
                'company.legal_person as legal_person',
                'company.cert_no as cert_no',
                'company.company_name as company_name',
                'bq.id as bq_id',
                'bq.batch_number as batch_number',
                'bq.money as money',
                'bq.duration as duration',
                'bq.repayment_type as repayment_type',
                'bq.status as status',
                'bq.create_time as create_time',
                'bq.update_time as update_time',
            ])
            ->order('bq_id','DESC')
            ->select();
        $count = BorrowRequest::alias('bq')
            ->where($where)
            ->where($where2)
            ->join('tp_user user', 'user.uid = bq.borrow_uid','left' )
            ->join('tp_user_company company', 'bq.borrow_uid = company.user_id','left' )
            ->count();
        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $int_page);

        $this->assign('repayment_type_map', BorrowRequest::repaymentTypeMap());
        $this->assign('status_map', BorrowRequest::statusMap());
        $this->assign('map_status', $arr_statusConfig);
        $this->assign('list', $list);
        $this->assign('pageElem', $paginator);
        return view('Borrower/companyBorrowList');
    }

    //个人原始借款、个人车贷、企业贷  删除功能
    public function deleteOne(){
        $int_id = Request::instance()->post('id');
        if (!$int_id){
            return $this->returnData(1, 'id传入失败');
        }
        $result = BorrowRequest::find($int_id);
        if ($result->status == BorrowRequest::STATUS_YES){
            return $this->returnData(1, '审核通过无法删除');
        }
        $result->delete();
        return $this->returnData(0, '删除成功');
    }

    //审核通过原始借款请求
    public function reviewBorrowRequest(){
        try{
            $int_uid = input('borrow_uid');
            $int_bqid = input('borrow_bqid');
            $obj_user = User::where('uid',$int_uid)->find();
            //按用户类型（1-个人，2-企业）来区分，个人按实名和设置支付密码，企业按新浪企业资质审核状态和设置支付密码
            $msg = '';
            if (!$obj_user) {
                $msg .= '无此用户；';
            }
            if ($obj_user->is_set_pay_password != 1) {
                $msg .= '未设置支付密码；';
            }
            if ($obj_user->user_type == 1) { //个人
                if ($obj_user && $obj_user->idcard && $obj_user->is_set_pay_password == 1){
                    $sql = BorrowRequest::where('id', $int_bqid)
                        ->where('borrow_uid', $int_uid)
                        ->setField('status', BorrowRequest::STATUS_YES);
                }else{
                    if (!$obj_user->idcard) {
                        $msg .= '未实名认证；';
                    }
                    return $this->returnData(1,'该用户状态无法审核通过:' . $msg);
                }
            } else { //企业
                $status = UserCompany::where('user_id', $int_uid)->value('status');
                if ($obj_user && $obj_user->is_set_pay_password == 1  && $status == 1){
                    $sql = BorrowRequest::where('id', $int_bqid)
                        ->where('borrow_uid', $int_uid)
                        ->setField('status', BorrowRequest::STATUS_YES);
                }else{
                    if ($status != 1) {
                        $msg .= '新浪企业资质审核未通过；';
                    }
                    return $this->returnData(1,'该用户状态无法审核通过:' . $msg);
                }
            }
                
            return $this->returnData(0,'ok' );
        }catch (\Exception $exception){
            return $this->returnData(1,'服务异常' );
        }
    }

    //设置支付密码后回调页面
    public function setPasswdSuccess(){
        try{
            $int_uid = input('borrow_uid');
            $obj_user = User::where('uid',$int_uid)->find();
            if ($obj_user && $obj_user->idcard
                && $obj_user->is_set_pay_password == 1){
                BorrowRequest::where('borrow_uid', $int_uid)
                    ->update(['status' =>BorrowRequest::STATUS_YES ]);
            }else{
                return $this->messageView('该用户状态无法审核通过');
            }
            return $this->successView();
        }catch (\Exception $exception){
            return $this->messageView('服务异常');
        }
    }

    //实名认证ajax
    public function realnameAjax(){
        try{
            $int_uid = $this->_Uid;
            $str_realname = Request::instance()->post('realname');
            $str_idcard = Request::instance()->post('idcard');
            if (!$int_uid || !$str_realname || !$str_idcard ){
                throw new \Exception('身份证，真实姓名 uid不能为空');
            }
            $res = UserService::userRealeNameObj($int_uid,$str_idcard,$str_realname);
            if($res['code'] == 0){
                return $this->returnData(0,'ok');
            }
            else{
                throw new \Exception($res['msg']);
            }
        }catch (\Exception $exception){
            return $this->returnData(1,$exception->getMessage(), []);
        }
    }

    private function checkInsertAccess($int_insertType){
        $userInfo = UserService::get_user();
        if(!in_array($int_insertType, $userInfo['merchant_show_type'])){
            return false;
        }
        return true;
    }

    /**
     * 存储在json里的字段按照分组 格式化数据
     * 例
     * [{
    "title": "借款人基本信息",
    "type": "1",
    "items": [{
    "title": "性别",
    "value": "男"
    },{
    "title": "其他平台借款金额",
    "value": "0"
    }]
    }, {
    "title": "借款人基本信息",
    "type": "1",
    "items": [{
    "title": "借款人简介",
    "value": "借款人为自然人，公司职员，工作收入稳定"
    }, {
    "title": "还款来源",
    "value": "工资收入"
    }]
    }]
     */
    private static function _formatJsonFieldGroup(&$arr_formatjson, $excel_key, $val, $map_excelSqlKey){
        $json_field = $map_excelSqlKey['json_map'][$excel_key];

        $int_fileGroupId =$json_field['group_id'];

        $arr_formatjson[$int_fileGroupId]['type'] = $map_excelSqlKey['json_filed_group_map'][$int_fileGroupId]['type'];
        $arr_formatjson[$int_fileGroupId]['title'] = $map_excelSqlKey['json_filed_group_map'][$int_fileGroupId]['title'];
        $arr_formatjson[$int_fileGroupId]['group_id'] = $int_fileGroupId;
        if(!array_key_exists('items',$arr_formatjson[$int_fileGroupId])){
            $arr_formatjson[$int_fileGroupId]['items'] = [];
        }
        $temp['title'] = $json_field['title'];
        $temp['field'] = $json_field['field'];
        $temp['value'] = $val;
        array_push($arr_formatjson[$int_fileGroupId]['items'], $temp);
    }

//======华丽的没有该功能=============================================

    //添加单个借款人模板
    public function add(){
        return view('Borrower/add');
    }
    //添加 独立借款人 消费贷 暂时不用
    public function addBorrowShopping(){
        return view('Borrower/addBorrowShopping');
    }
    //导入结果显示
    public function excleImportResult(){

    }
    /*//批量借款模板
    public function count_add(){
        $UpYun = require(APP_COMMON . 'conf/upyun_config.php');
        $this->assign([
         'upyun'=>$UpYun['UPYUN_CONFIG']['UPAIYUN'],
        ]);
        return view('Borrower/count_add');
    }*/
    //个人借款批量添加
    private function _addPerson($arr_date){
        $user = new BorrowRequest();
        $res = $user->saveAll($arr_date, false);
        return $res;
    }

}